import axios from 'axios';

import dotenv from 'dotenv';
dotenv.config();

import { supabase } from '../src/lib/supabase';
import { log } from 'console';

const API_URL = 'http://218.76.9.139:8535/v1/workflows/run';
const API_KEY = 'app-7d5K583sopfWMvVrjZbz85FW';

interface ProcessImageOptions {
  imageUrl: string;
  user?: string;
}

interface APIResponse {
  imageUrl?: string;
  title?: string;
  content?: string;
}

export async function processImage(options: ProcessImageOptions): Promise<string> {
  const { imageUrl, user = 'huiqi0126' } = options;
  // console.log(`Processed: `,imageUrl,user);

  try {
    // 构建 JSON 数据
    const data = {
      inputs: {
        images: {
          transfer_method: 'remote_url',
          url: imageUrl,
          type: 'image'
        }
      },
      response_mode: 'blocking',
      user: user,
    };
    const response = await axios.post(API_URL, data, {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    const { imageUrl: resultImageUrl, title, content } = response.data.data.outputs;
    // console.log('insert data=======', resultImageUrl,title,content);
    if (resultImageUrl && content.length>200 && title.length>8) {
      const { error } = await supabase
        .from('table_data')
        .insert({
          imageUrl: resultImageUrl,
          title: title || '',
          content: content || ''
        });

      if (error) {
        throw new Error(`Database Error: ${error.message}`);
      }
    }

    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      throw new Error(`API Error: ${error.response?.data?.message || error.message}`);
    }
    throw error;
  }
}

// 使用示例
// processImage({ imageUrl: 'https://example.com/image.jpg' })
//   .then(result => console.log(result))
//   .catch(error => console.error(error));
